<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>car</title>
  <style>
    body {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }

    #main {
      height: 500px;
      width: 800px;
      border: 1px solid #ccc;
    }
  </style>
</head>

<body>
  <div id="main">

  </div>
  <script src="matter.js"></script>
  <script src="matter-wrap.js"></script>
  <script>
    Matter.use('matter-wrap')
    const { Engine, Render, Bodies, Example, Composites, Common, Composite, Events, Body, Mouse, MouseConstraint, Constraint } = Matter;
    const main = document.querySelector('#main');
    // 创建引擎
    const engine = Engine.create();

    // 创建渲染器
    const render = Render.create({
      element: main,
      engine: engine,
      options: {
        width: main.offsetWidth,
        height: main.offsetHeight,
        showAngleIndicator: true,
        showCollisions: true,
      }
    });
    // 创建世界（包含所有物体）
    const world = engine.world;
    // 创建鼠标约束
    const mouse = Mouse.create(render.canvas);
    const mouseConstraint = MouseConstraint.create(engine, {
      mouse: mouse,
      constraint: {
        stiffness: 1,
        render: {
          visible: false
        }
      }
    });
    Composite.add(world, mouseConstraint);
    const eleWidth = main.offsetWidth;
    const eleHeight = main.offsetHeight;
    var stack = Composites.stack(100, 0, 5, 2, 0, 0, function (x, y) {
      return Bodies.circle(x, y, Common.random(10, 20), { restitution: 0.6, friction: 0.1 });
    });
    for (let i = 0; i < stack.bodies.length; i++) {
      stack.bodies[i].plugin.wrap = {
        min: { x: 0, y: 0 },
        max: { x: eleWidth, y: eleHeight }
      };
    }
    Composite.add(world, stack)
    let car = createCar(60, eleHeight - 50, 100, 30, 30)
    Composite.add(world, car);
    console.log(car)
    var forceMagnitude = 0.1; // 调整这个值来控制小车的前进速度
    var carBody = car.bodies[0];
    // 应用力
    // Body.applyForce(carBody, { x: carBody.position.x, y: carBody.position.y }, { x: forceMagnitude, y: 0 });
    car.plugin.wrap = { //复合体的要单独加
      min: { x: 0, y: 0 },
      max: { x: eleWidth, y: eleHeight }
    };

    Composite.add(world, Bodies.rectangle(eleWidth / 2, 0, eleWidth * 2, 50, { isStatic: true, friction: 0.01, angle: Math.PI * 0.001, }))
    Composite.add(world, Bodies.rectangle(eleWidth / 2, eleHeight, eleWidth * 2, 50, { isStatic: true, friction: 0.01, angle: Math.PI * 0.001, }))
    // 启动引擎和渲染器
    Engine.run(engine);
    Render.run(render);
    window.addEventListener('keydown', (e) => {
      if (e.keyCode === 37) { //上下左右键
        Body.applyForce(carBody, { x: carBody.position.x, y: carBody.position.y }, { x: -forceMagnitude, y: 0 });
      } else if (e.keyCode === 39) {
        Body.applyForce(carBody, { x: carBody.position.x, y: carBody.position.y }, { x: forceMagnitude, y: 0 });
      } else if (e.keyCode === 38) {
        Body.applyForce(carBody, { x: carBody.position.x, y: carBody.position.y }, { x: 0, y: -forceMagnitude });
      } else if (e.keyCode === 40) {
        Body.applyForce(carBody, { x: carBody.position.x, y: carBody.position.y }, { x: 0, y: forceMagnitude });
      }
    })
    // 小车集合体
    function createCar(xx, yy, width, height, wheelSize) {
      var Body = Matter.Body,
        Bodies = Matter.Bodies,
        Composite = Matter.Composite,
        Constraint = Matter.Constraint;

      var group = Body.nextGroup(true),
        wheelBase = 20,
        wheelAOffset = -width * 0.5 + wheelBase,
        wheelBOffset = width * 0.5 - wheelBase,
        wheelYOffset = 0;

      var car = Composite.create({ label: 'Car' }),
        body = Bodies.rectangle(xx, yy, width, height, {
          collisionFilter: {
            group: group
          },
          chamfer: {
            radius: height * 0.5
          },
          density: 0.0001
        });

      var wheelA = Bodies.circle(xx + wheelAOffset, yy + wheelYOffset, wheelSize, {
        collisionFilter: {
          group: group
        },
      });

      var wheelB = Bodies.circle(xx + wheelBOffset, yy + wheelYOffset, wheelSize, {
        collisionFilter: {
          group: group
        },
      });

      var axelA = Constraint.create({
        bodyB: body,
        pointB: { x: wheelAOffset, y: wheelYOffset },
        bodyA: wheelA,
        stiffness: 1,
        length: 0
      });

      var axelB = Constraint.create({
        bodyB: body,
        pointB: { x: wheelBOffset, y: wheelYOffset },
        bodyA: wheelB,
        stiffness: 1,
        length: 0
      });

      Composite.addBody(car, body);
      Composite.addBody(car, wheelA);
      Composite.addBody(car, wheelB);
      Composite.addConstraint(car, axelA);
      Composite.addConstraint(car, axelB);

      return car;
    };
  </script>
</body>

</html>